import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.*;

/**
 * Created by dell on 2017/8/10.
 */
public class Picture {
    public static void main(String[] args) throws FileNotFoundException {
        copyPictureToFile("http://img.mmjpg.com/2016/", 550, 580, ".jpg", "美美女图片", 1, 40);
//        loadPictureToFile("http://img.mmjpg.com/2017/",1007,
//                1008,".jpg","1美图片",1,5);
    }

    /**
     * 测试
     *
     * @param
     * @param fileType
     * @param pictureName
     */

    public static void copyPictureToFile(String net, int picturePage, int maxPage, String fileType, String pictureName, int startNum, int downLoadPictureNum) throws FileNotFoundException {
        int count = 0;
        for (int j = picturePage; j < maxPage; j++) {
            for (int i = startNum; i < downLoadPictureNum; i++) {
                String url = net + j + "/" + i + fileType;
                byte[] btImg = getImageFromNetByUrl(url, net + j);
                if (null != btImg && btImg.length > 0) {
                    System.out.println("读取到：" + btImg.length + " 字节");
                    String fileName = pictureName + j + "_" + i + fileType;
                    writeImageToDisk(btImg, fileName);
                    System.out.println("address " + url + "is loaded");
                } else {
                    System.out.println("没有从该连接获得内容");
                }
                count++;
                if (count == 100) {
                    System.out.println("复制完成");
                    return;
                }
            }
        }
    }

    /**
     * 将图片写入到磁盘
     *
     * @param img      图片数据流
     * @param fileName 文件保存时的名称
     */
    public static void writeImageToDisk(byte[] img, String fileName) {
        try {
            File file = new File("F:/图片/" + fileName);
            FileOutputStream fops = new FileOutputStream(file);
            fops.write(img);
            fops.flush();
            fops.close();
            System.out.println("图片已经写入到F盘");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据地址获得数据的字节流
     *
     * @param strUrl 网络连接地址
     * @return
     */
    public static byte[] getImageFromNetByUrl(String strUrl, String referer) {
        try {
//            URL url = new URL(strUrl);
//            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//            conn.setRequestMethod("GET");
//            conn.setConnectTimeout(5 * 1000);
//            conn.setDoOutput(true);
//            conn.setDoInput(true);
//            //conn.setRequestMethod("POST");
//            conn.setUseCaches(false);
//            conn.setInstanceFollowRedirects(true);
//            conn.setRequestProperty("Referer", referer);
//            conn.setRequestProperty(" User-Agent ",
//                    " Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36 ");
//            //hu.setChunkedStreamingMode(5);
//            conn.connect();
            OkHttpClient okHttpClient = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(strUrl).addHeader("Referer", referer)
                    .build();
            //final Call call = okHttpClient.newCall(request);
            String net = strUrl;
            Response response = okHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                System.out.println(response.code());
            } else {
                response.body().close();
                throw new IOException("Unexpected code" + response);
                //new OkGetPicture().loadPictureToFile(url,page,startNum+1,loadPictureToFile,j,i++,pictureName);
            }
//                        InputStream inStream =conn .getInputStream();//通过输入流获取图片数据
            InputStream is = response.body().byteStream();
            byte[] btImg = readInputStream(is);
            //byte[] btImg = readInputStream(inStream);//得到图片的二进制数据
            return btImg;
        } catch (Exception e) {
            System.out.println("下一页");
        }
        return null;
    }

    /**
     * 从输入流中获取数据
     *
     * @param inStream 输入流
     * @return
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }

}
